package com.ja.openchat.views;

import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.group.GroupSendActivity;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.ui.contact.ContactChooseAdapter;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ContactGroupSendDialog extends BaseBottomDialog{

    private RecyclerView recyclerView;
    private ContactChooseAdapter contactChooseAdapter;
    private List<UserInfo> contactList = new ArrayList<>();
    private Map<Long, UserInfo> choosedDic = new HashMap<>();
    private Map<Long, UserInfo> disableChooseDic = new HashMap<>();
    private List<Section> sectionList = new ArrayList<>();

    //从联系人详情创建群组
    private long fromContactId;

    private boolean allSeleter = false;

    private View checkView;
    private SideIndexBar slide;

    private ContactChooseActivity.ContactChooseType chooseType;

    public ContactGroupSendDialog(@NonNull Context context,ContactChooseActivity.ContactChooseType chooseType, OnItemClickListner listner) {
        super(context);
        this.chooseType = chooseType;
    }

    public ContactGroupSendDialog(@NonNull Context context,ContactChooseActivity.ContactChooseType chooseType, long fromContactId,OnItemClickListner listner) {
        super(context);
        this.chooseType = chooseType;
        this.fromContactId = fromContactId;
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_group_send_view;
    }


    @Override
    protected void onCreate() {
        super.onCreate();
        TextView tvTitle = findViewById(R.id.tv_title);
        String title = fromContactId != 0 ? getContext().getString(R.string.select_friend) : getContext().getString(R.string.create_group);
        tvTitle.setText(title);
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayout larSeleter = findViewById(R.id.larSeleter);
        checkView = findViewById(R.id.checkView);
        CustomEditText etSearch = findViewById(R.id.et_search);
        slide = findViewById(R.id.slide);
        findViewById(R.id.tv_cancel).setOnClickListener(v -> {dismiss();});
        findViewById(R.id.tv_save).setOnClickListener(v -> {
            //完成
            if(chooseType == ContactChooseActivity.ContactChooseType.ContactChooseType_CreateSuperGroup){
                //首页新建群聊
                createGroup();
            }else if(chooseType == ContactChooseActivity.ContactChooseType.ContactChooseType_CreateGroupSend){
                //群发助手 创建群聊
                createGroupSend();
            }
        });
        initListView();
        loadData();
        larSeleter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                allSeleter = !allSeleter;
                checkView.setSelected(allSeleter);
                if(allSeleter){
                    for (int i=0;i<sectionList.size();i++){
                        Object obj = sectionList.get(i).getObject();
                        if (obj instanceof UserInfo) {
                            UserInfo user = (UserInfo) obj;
                            choosedDic.put(user.id, user);
                        }
                    }
                }else {
                    choosedDic.clear();
                }
                contactChooseAdapter.notifyDataSetChanged();
            }
        });
        //索引事件
        slide.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        //点击事件
        contactChooseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        if (disableChooseDic.get(user.id) == null) {//不在不可更改的列表里
                            if (choosedDic.get(user.id) != null) {
                                choosedDic.remove(user.id);
                            } else {
                                choosedDic.put(user.id, user);
                            }
                            //刷新多选按钮状态
                            freshAllSelStyle();
                            contactChooseAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
        contactChooseAdapter.setOnChooseListener(new ContactChooseAdapter.OnChooseListener() {
            @Override
            public boolean isSignalMode() {
                return false;
            }

            @Override
            public boolean isChoose(UserInfo user) {
                //多选
                return choosedDic.get(user.id) != null;
            }

            @Override
            public boolean showMask(UserInfo user) {
                //多选
                return disableChooseDic.get(user.id) != null;
            }
        });
        //输入框监听
        etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });

    }

    private void freshAllSelStyle(){
        boolean allSel = true;
        for (int i=0;i<sectionList.size();i++){
            Object obj = sectionList.get(i).getObject();
            if (obj instanceof UserInfo) {
                UserInfo user = (UserInfo) obj;
                if (choosedDic.get(user.id) == null) {//没有
                    allSel = false;
                }
            }
        }
        allSeleter = allSel;
        checkView.setSelected(allSeleter);
    }

    private void initListView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        contactChooseAdapter = new ContactChooseAdapter(R.layout.adapter_choose_contact_list, R.layout.adapter_section_contact_list, sectionList);
        recyclerView.setAdapter(contactChooseAdapter);
    }

    private void loadData() {
        contactList.clear();
        //不可更改部分
        if (fromContactId != 0) {
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(fromContactId);
            if (user != null) {
                choosedDic.put(user.id, user);
                disableChooseDic.put(user.id, user);
            }
        }
        List<UserInfo> userInfos = TelegramManager.getTelegramManager().getTgData().getMyContacts();
        if(userInfos!=null&&userInfos.size()>0){
            if(fromContactId==0){
                for(UserInfo userInfo:userInfos){
                    if(userInfo.id!=UserInfo.getUserInfo().id){
                        contactList.add(userInfo);
                    }
                }
            }else{
                contactList.addAll(userInfos);
            }
        }
        //联系人列表

        reloadContacts(contactList);
    }

    private void reloadContacts(List<UserInfo> list) {
        sectionList.clear();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<UserInfo>() {
                @Override
                public int compare(UserInfo u1, UserInfo u2) {
                    if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                        return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                    }
                    return 0;
                }
            });
        }
        //生成a-z hash
        Map<String, List<UserInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        Map<String, String> defaultMap = new HashMap<>();
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    defaultMap.put(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0)),"");
//                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    defaultMap.put("#","");
//                    sectionMap.get("#").add(user);
                }
            } else {
//                sectionMap.get("#").add(user);
                defaultMap.put("#","");
            }
        }
        List<String> keyList = new ArrayList<>(defaultMap.keySet());
        String[] keys = keyList.toArray(new String[]{} );
        slide.DEFAULT_INDEX_ITEMS = keys;
        slide.setEnableItemHeight(true);
        slide.refresh();

        //插入userinfo
        for (UserInfo user : list) {
            if (!StringUtils.isEmpty(user.displayName_full_py)) {
                if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                    sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                } else {
                    sectionMap.get("#").add(user);
                }
            } else {
                sectionMap.get("#").add(user);
            }
        }
        //ui数据
        for (String azIndex : slide.DEFAULT_INDEX_ITEMS) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (UserInfo user : sectionMap.get(azIndex)) {
                    sectionList.add(new Section(false, user));
                }
            }
        }
        //刷新页面
        contactChooseAdapter.notifyDataSetChanged();
    }

    private void doSearch(String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            List<UserInfo> list = new ArrayList<>();
            for (UserInfo user : contactList) {
                if (user.isMatch(keyword)) {
                    list.add(user);
                }
            }
            reloadContacts(list);
        } else {
            reloadContacts(contactList);
        }
    }

    private void createGroupSend() {
        if (choosedDic.size() < 2) {
            showErrorTip(getContext().getString(R.string.create_group_condition));
            return;
        }
        Set<Map.Entry<Long,UserInfo>> choosedSets = choosedDic.entrySet();
        ArrayList<Long> userIds = new ArrayList<>();
        for(Map.Entry<Long,UserInfo> entry:choosedSets){
            TelegramManager.getTelegramManager().createPrivateChat(getContext(),entry.getValue().id,null);
            userIds.add(entry.getValue().id);
        }
        ChatActivity.startActivity((Activity) getContext(),new GroupSendInfo(userIds), GroupSendActivity.REQUEST_CODE_FOR_GROUP_SEND);

        dismiss();
    }

    private void createGroup() {
        if (choosedDic.size() < 2) {
            showErrorTip(getContext().getString(R.string.create_group_condition));
            return;
        }
        List<UserInfo> list = new ArrayList<>(choosedDic.values());
        Collections.sort(list, new Comparator<UserInfo>() {
            @Override
            public int compare(UserInfo u1, UserInfo u2) {
                if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                    return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                }
                return 0;
            }
        });
        //创建群组
        showProgress();
        TelegramManager.getTelegramManager().createSuperGroupChat(getContext(), list, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj.ok) {
                    ChatActivity.startActivity(getContext(), (ChatInfo) obj.data);
                    dismiss();
                } else {
                    showErrorTip(getContext().getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getContext().getString(R.string.request_error));
            }
        });
    }


    @Override
    protected void onShow() {
        super.onShow();
    }

    @Override
    protected void onDismiss() {
        super.onDismiss();
    }

    @Override
    protected int getMaxHeight() {
        return (int) (XPopupUtils.getAppHeight(getContext()) * 0.98f);
    }


    public interface OnItemClickListner {
        void clickPostion(LocalMessageInfo messageInfo, GroupSendInfo groupSendInfo);
    }

}
